/*
 * Copyright (c) 2023, 2023,yzc.cn All rights reserved.
 *
 */
package cn.yzc.utils;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>Project: SpringPro - BeanFactory</p>
 * <p>Powered by yzc On 2023-10-17 16:18:46</p>
 * <p>描述：<p>
 *
 * @author yzc [yzc0415@126.com]
 * @version 1.0
 * @since 17
 */
public class BeanFactory {
    private static Map beanMap = new ConcurrentHashMap();

    static {
        InputStream is = BeanFactory.class.getClassLoader().getResourceAsStream("beans.properties");
        Properties prop = new Properties();
        try {
            prop.load(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println();

        //遍历properties
        prop.forEach((key, value) -> {
            System.out.println(key);
            //利用反射实例化
            try {
                Class clazz = Class.forName((String) value);
                Constructor con = clazz.getConstructor();
                //实例化
                Object obj = con.newInstance();
                //存入内存中
                beanMap.put(key, obj);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        });
    }

    public static Object getBean(String name) {
        if (beanMap.containsKey(name)) {
            return beanMap.get(name);
        }
        return null;
    }
}
